package com.bdcom.autotest.util;

import com.bdcom.autotest.telnet.util.ping.OSinfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class RunScriptUtil {

    /**
     * 脚本运行 辅助类
     * @author Guodeqi
     *
     */

        private static final Log logger = LogFactory.getLog(RunScriptUtil.class);

        public static final String SCRIPT_SUFFIX_LINUX = ".sh";
        public static final String SCRIPT_SUFFIX_WINDOWS = ".bat";

        public static final String FILE_SEP = "/";


        /**
         * 稍总结了一下：Windows下的批处理：cd /d %~dp0.%~dp0表示此批处理的目录，
         * /d表示切换目录的同时也切换盘符.
         * Linux下shell：cd 'dirname $0' ;
         *
         * @param dirPath 脚本目录
         * @param scriptName	脚本名称,不带后缀
         * @return
         * @throws IOException
         * @throws InterruptedException
         */
        public static boolean runScript( String dirPath, String scriptName ) throws IOException, InterruptedException{

            String scriptSuffix = "";
            String command = "";
            String userDir = System.getProperty("user.dir");
            userDir = userDir.replaceAll("\\\\", "/");
            if( OSinfo.isWindows() ){
                scriptSuffix = SCRIPT_SUFFIX_WINDOWS;
                command = "cmd /c \""+ dirPath +scriptName+scriptSuffix +"\"";
                Runtime runtime = Runtime.getRuntime();
                Process exec = runtime.exec(command);
            }else if(  OSinfo.isLinux() ){
                command = dirPath + scriptName;
                Runtime runtime = Runtime.getRuntime();
                Process exec = runtime.exec(command);
                // 打印程序输出
                readProcessOutput(exec);
            }else if(  OSinfo.isMacOSX() ){
                command = dirPath + scriptName;
                //解决脚本没有执行权限
                ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "777",command);
                Process process = builder.start();
                process.waitFor();
            }
            logger.info("***** command: "+ command + "  run finished.");
            return true;

        }



        /**
         * 打印进程输出
         *
         * @param process 进程
         */
        private static void readProcessOutput(final Process process) {
            // 将进程的正常输出在 System.out 中打印，进程的错误输出在 System.err 中打印
            read(process.getInputStream(), System.out);
            read(process.getErrorStream(), System.err);
        }

        // 读取输入流
        private static void read(InputStream inputStream, PrintStream out) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public static boolean checkTCPPortIsInUse( int port ) {
            return checkPortIsInUse( "tcp" , port );
        }

        public static boolean checkUDPPortIsInUse( int port ) {
            return checkPortIsInUse( "udp" , port );
        }


        public static boolean checkPortIsInUse(String  protocal, int port ) {
            try {

                if( "tcp".equals(protocal) ){
                    try {
                        Socket socket = new Socket( InetAddress.getByName("127.0.0.1"), port);
                        socket.close();
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }

                if( OSinfo.isWindows() ){

                    String cmd = "cmd.exe /c netstat -ano | findstr \"" + port+"\"";
                    Runtime runtime = Runtime.getRuntime();
                    Process exec = runtime.exec(cmd);
                    InputStream inputStream = exec.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[256];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    String result = new String( baos.toByteArray() );
                    baos.close();

                    if( result!=null ){
                        String lowerCaseResult = result.toLowerCase();
                        String portStr = port+"";
                        int portStrlength = portStr.length();
                        String[] split = lowerCaseResult.split("\r");
                        for( int i=0 ; i<split.length ; i++  ){
                            String tmpLine = split[i];
                            int indexOf = tmpLine.indexOf(protocal);
                            if( indexOf != -1 ){
                                int portIndex = tmpLine.indexOf(portStr);
                                String beforeChar = tmpLine.substring( portIndex-1  , portIndex);
                                String nextChar = tmpLine.substring( portIndex+portStrlength , portIndex +portStrlength+1);
                                if( ":".equals(beforeChar) &&  "".equals(nextChar.trim()) ){
                                    return true;
                                }
                            }
                        }
                    }
                }else if( OSinfo.isLinux() ){


                    String cmd = "lsof -i:"+ port;
                    Runtime runtime = Runtime.getRuntime();
                    Process exec = runtime.exec(cmd);
                    InputStream inputStream = exec.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[256];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    String result = new String( baos.toByteArray() );
                    baos.close();

                    if( result!=null ){
                        String lowerCaseResult = result.toLowerCase();
                        String portStr = port+"";
                        int portStrlength = portStr.length();
                        String[] split = lowerCaseResult.split("\n");
                        for( int i=0 ; i<split.length ; i++  ){
                            String tmpLine = split[i];
                            int indexOf = tmpLine.indexOf(protocal);
                            if( indexOf != -1 ){

                                return true;

                            }
                        }
                    }


                }
                else if( OSinfo.isMacOSX() ){
                    String cmd = "lsof -i:"+ port;
                    Runtime runtime = Runtime.getRuntime();
                    Process exec = runtime.exec(cmd);
                    InputStream inputStream = exec.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[256];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                    String result = new String( baos.toByteArray() );
                    baos.close();

                    if( result!=null ){
                        String lowerCaseResult = result.toLowerCase();
                        String portStr = port+"";
                        int portStrlength = portStr.length();
                        String[] split = lowerCaseResult.split("\n");
                        for( int i=0 ; i<split.length ; i++  ){
                            String tmpLine = split[i];
                            int indexOf = tmpLine.indexOf(protocal);
                            if( indexOf != -1 ){

                                return true;

                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("", e);
            }
            return false;
        }



        public static void main(String[] args) throws IOException, InterruptedException {

//		String userDir = System.getProperty("user.dir");
//		System.out.println( userDir.replaceAll("\\\\", "/") );
//		boolean runScript = runScript("bin", "startnms");
//		System.out.println( runScript  );

            System.out.println(  checkUDPPortIsInUse(61445)  );

//		System.out.println(   checkTCPPortIsInUse(8889)   );

        }


}
